/**
 * 
 */
package vn.smartware.co.framework.action;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;

import vn.smartware.co.framework.bean.LoginDTO;
import vn.smartware.co.framework.exception.FatalException;
import vn.smartware.co.framework.exception.ServerException;
import vn.smartware.co.framework.exception.SessionTimeOutException;
import vn.smartware.co.framework.form.ActionForm;
import vn.smartware.co.framework.form.LoginForm;
import vn.smartware.co.framework.plugin.LangResources;
import vn.smartware.co.framework.swt.base.SWTRelogin;
import vn.smartware.co.java.net.commons.Utils;


/**
 * Requester
 * @author thuctt
 */
public class Requester {

	/**
	 * execute action method
	 * @param form
	 * @param shell
	 * @return ActionForm
	 * @throws FatalException 
	 * @throws ServerException 
	 * @throws SessionTimeOutException 
	 */
	public static ActionForm execute(ActionForm form, Shell shell)
			throws FatalException, ServerException {
		
		RequestProcesser proc = new RequestProcesser();
		try {
			form = proc.execute(form);
			
		} catch (SessionTimeOutException e) {
			if (Utils.isNullEmpty(form.getAppName())
					|| !form.getAppName().equals(LangResources.getText("SWTRelogin.shell"))){
				LoginForm loginForm = new LoginForm();
				loginForm.setSessionTimeout(true);
				loginForm.setUserDTO(LoginDTO.getInstance());
				SWTRelogin reLogin = new SWTRelogin(shell);
				reLogin.setSearchCriteria(loginForm);
				if (!loginForm.isSessionTimeout()){
					form = execute(form);
				}else{
					throw e;
				}
			}else{
				form = execute(form);
			}
			
		}
		return form;
	}

	/**
	 * execute a form
	 * @param form
	 * @return ActionForm
	 * @throws FatalException 
	 * @throws ServerException 
	 * @throws SessionTimeOutException 
	 */
	public static ActionForm execute(ActionForm form) throws FatalException,
			ServerException, SessionTimeOutException {
		
		RequestProcesser proc = new RequestProcesser();
		form = proc.execute(form);
			
		return form;
	}

	/**
	 * execute
	 * @param form
	 * @param composite
	 * @return ActionForm
	 * @throws FatalException
	 * @throws ServerException 
	 */
	public static ActionForm execute(ActionForm form, Composite composite)
			throws FatalException, ServerException {
		
		RequestProcesser proc = new RequestProcesser();
		try {
			form = proc.execute(form);
			
		} catch (SessionTimeOutException e) {
			
			LoginForm loginForm = new LoginForm();
			loginForm.setSessionTimeout(true);
			loginForm.setUserDTO(LoginDTO.getInstance());
			SWTRelogin reLogin = new SWTRelogin(composite.getShell());
			reLogin.setSearchCriteria(loginForm);
			
			if (!loginForm.isSessionTimeout()){
				form = execute(form);
			}else{
				throw e;
			}
		}
		return form;
	}
}
